package com.example.dragon.adpter;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.example.dragon.bean.OrderBean;
import com.example.dragon.common.Common;
import com.example.dragon.dialog.MessageDialog;
import com.example.dragon.dialog.WaitDialog;
import com.example.dragon.view.MyRecyclerView;
import com.example.dragon.xmf.MainActivity;
import com.example.dragon.xmf.R;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import io.github.erehmi.countdown.CountDownTask;
import io.github.erehmi.countdown.CountDownTimers;
import okhttp3.Call;

import static com.mob.MobSDK.getContext;

/**
 * Created by Dragon on 2017/6/20.
 */

public class PengDingAdpter extends RecyclerView.Adapter {

    private List<OrderBean> orderBeanList = new ArrayList<>();
    private List<OrderBean> mdrivesList = new ArrayList<>();
    private PdDriverAdpter pdDriverAdpter;
    private int recLen = 0;
    Context mcontext;
    private MessageDialog messageDialog;
    WaitDialog mwaitDialog;
    Handler handler = new Handler();
    long targetMillis = CountDownTask.elapsedRealtime() + 1000 * 60;
    Runnable runnable;
    CountDownTask countDownTask = CountDownTask.create();


    public PengDingAdpter(Context mcontext,List<OrderBean> orderBeanList) {
        this.mcontext = mcontext;
        this.orderBeanList=orderBeanList;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(mcontext).inflate(R.layout.orders_item_layout, parent, false);
        mwaitDialog = new WaitDialog(mcontext,"2");
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        final OrderBean item = orderBeanList.get(position);

        final ViewHolder viewHolder = (ViewHolder) holder;
        if (item != null) {
            viewHolder.pdorderId.setText(item.getOrders_id());
            viewHolder.pdadress.setText(item.getAddress());
            viewHolder.pddate.setText(item.getWorktime());
            Log.i("dis",item.getLat()+"---"+item.getLng());
            final int CD_INTERVAL = 1000;

            countDownTask.until(viewHolder.timepicker, targetMillis, CD_INTERVAL, new CountDownTimers.OnCountDownListener() {
                @Override
                public void onTick(View view, long millisUntilFinished) {
                    ((TextView)view).setText(String.valueOf(millisUntilFinished / CD_INTERVAL));
                }
                @Override
                public void onFinish(View view) {
                    ((TextView)view).setText("请等待.");
                    countDownTask.cancel();
                }
            });
//             runnable = new Runnable() {
//                @Override
//                public void run() {
//                    handler.postDelayed(this, 1000);
//                    recLen++;
//                    if (recLen>60){
//                        viewHolder.timepicker.setText("请等待");
//                        Message message = new Message();
//                        message.what = 1;
//                        handlerStop.sendMessage(message);
//                    }else {
//                        viewHolder.timepicker.setText("" + recLen);
//                    }
//
//                }
//            };
//            handler.postDelayed(runnable, 1000);
            viewHolder.pdcanleBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    canleOrder(item.getOrders_id());
                }
            });
            if (null==(item.getDrivers())){

            }else {
                try {
                    JSONArray drivers = item.getDrivers();
                    mdrivesList.clear();
                    for (int i= 0; i<drivers.length();i++){
                        JSONObject jsonObject = drivers.getJSONObject(i);
                        mdrivesList.add(new OrderBean(
                                jsonObject.getString("driver_id"),
                                item.getOrders_id(),
                                jsonObject.getString("avatar"),
                                jsonObject.getString("name"),
                                jsonObject.getString("lng"),
                                jsonObject.getString("lat"),
                                jsonObject.getString("stars"),
                                item.getLng(),
                                item.getLat()
                        ));
                        Log.i("stars",jsonObject.getString("stars"));
                    }

                }catch (JSONException e) {
                    e.printStackTrace();
                }
                pdDriverAdpter = new PdDriverAdpter(mcontext,mdrivesList);
                viewHolder.pddriverRecy.setAdapter(pdDriverAdpter);
            }


        }
    }
    final Handler handlerStop = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    recLen = 0;
                    handler.removeCallbacks(runnable);
                    break;
            }
            super.handleMessage(msg);
        }

    };
    private void canleOrder(String oid){
        mwaitDialog.show();
        OkHttpUtils.post()
                .url(Common.MIFENG_URL+"Orders&a=cancel")
                .addParams("token", MainActivity.TOKEN)
                .addParams("orders_id",oid)
                .build()//
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.i("res",e.toString());
                    }
                    @Override
                    public void onResponse(String response, int id) {
                        mwaitDialog.dismiss();
                        Log.i("res",response.toString());
                        try {
                            JSONObject jsonObject =new JSONObject(response);
                            int code = jsonObject.getInt("code");
                            if (code==200){
                                messageDialog = new MessageDialog("",jsonObject.getString("message"),"确定",mcontext);
                                notifyDataSetChanged();
                            }else {
                                messageDialog = new MessageDialog("",jsonObject.getString("message"),"确定",mcontext);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }


    @Override
    public int getItemCount() {
        return orderBeanList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView pddate,pdadress,pdorderId,timepicker;
        Button pdcanleBtn;
        RecyclerView pddriverRecy;
        public ViewHolder(View itemView) {
            super(itemView);
            timepicker = (TextView)itemView.findViewById(R.id.timepicker);
            pddate = (TextView)itemView.findViewById(R.id.pdwoketime_Text);
            pdadress =(TextView)itemView.findViewById(R.id.pdAdress_text);
            pdorderId = (TextView)itemView.findViewById(R.id.pdidText);
            pdcanleBtn = (Button)itemView.findViewById(R.id.pdcancle_Btn);
            pddriverRecy = (RecyclerView) itemView.findViewById(R.id.pddriverRecy);
            pddriverRecy.setLayoutManager(new LinearLayoutManager(mcontext,LinearLayoutManager.VERTICAL,true));
            pddriverRecy.setItemAnimator(new DefaultItemAnimator());
            pddriverRecy.setNestedScrollingEnabled(false);
        }
    }
}
